package com.smasher.update.component.check

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import com.google.gson.GsonBuilder
import com.smasher.core.log.ToastUtil
import com.smasher.update.api.Api
import com.smasher.update.entity.BeanVersion
import com.smasher.update.executor.LoongExecutor
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.InternalSerializationApi
import org.json.JSONObject

class CheckInfoImplSoftOut(context: Context) : CheckDelegate, Handler.Callback {

    private val mApi = Api()
    private var silent = false
    private val gson = GsonBuilder().create()
    private var onCheckListener: OnCheckListener? = null
    private var mContext: Context? = null

    private val mainThreadHandler: Handler = Handler(Looper.getMainLooper(), this)


    init {
        mContext = context
    }


    override fun checkVersion(
        ruleId: String,
        code: Long,
        onCheckListener: OnCheckListener
    ) {
        this.onCheckListener = onCheckListener
        silent = false
        checkInReal(ruleId, code)
    }

    override fun checkVersion(
        ruleId: String,
        code: Long,
        silent: Boolean,
        onCheckListener: OnCheckListener
    ) {
        this.onCheckListener = onCheckListener
        this.silent = silent
        checkInReal(ruleId, code)
    }

    @OptIn(InternalSerializationApi::class)
    private fun checkInReal(ruleId: String, code: Long) {

        LoongExecutor.getInstance().execute {

            runBlocking {
                val result = try {
                    Result.success(mApi.getVersion(URL, ruleId, code))
                } catch (error: Exception) {
                    Result.failure(error)
                }
                var resultType = 0
                var target: JSONObject? = null
                var message = ""

                if (result.isSuccess) {
                    Log.i(TAG, "checkVersion: success ")
                    val container = result.getOrNull()
                    val version = container?.data

                    if (version == null) {
                        resultType = 0
                        message = container?.msg ?: ""
                    } else {
                        resultType = 1
                        target = createJSONObject(version)
                    }
                } else {
                    val error = result.exceptionOrNull()
                    Log.e(TAG, "checkVersion: error = ${error?.message} ", error)
                    resultType = 2
                    message = "暂无更新"
                }
                val loong = Message.obtain().apply {
                    what = WHAT_UPDATE
                    arg1 = resultType
                    obj = when (resultType) {
                        1 -> target
                        else -> message
                    }
                }
                mainThreadHandler.sendMessage(loong)
            }
        }
    }

    @OptIn(InternalSerializationApi::class)
    private fun createJSONObject(version: BeanVersion): JSONObject? {
        try {
            val json = gson.toJson(version)
            return JSONObject(json)
        } catch (e: Exception) {
            Log.e(TAG, e.message.toString())
        }
        return null
    }


    override fun release() {
        mContext = null
        mainThreadHandler.removeCallbacksAndMessages(null)
    }

    companion object {
        const val TAG = "CheckCRMImpl"

        private const val WHAT_UPDATE = 8000
        private const val URL = "http://softout.beizhi365.com/api/version/checkVersion"
    }


    override fun handleMessage(msg: Message): Boolean {
        if (msg.what == WHAT_UPDATE) {
            var json: JSONObject = when (msg.obj) {
                is JSONObject -> msg.obj as JSONObject
                else -> JSONObject()
            }
            var message: String = when (msg.obj) {
                is String -> msg.obj as String
                else -> "暂无更新"
            }

            when (msg.arg1) {
                0 -> {
                    Log.i(TAG, "checkVersion: $json ")
                    onCheckListener?.onCheck(json)
                    if (!silent) {
                        ToastUtil.info(mContext, message)
                    }
                }

                1 -> {
                    Log.i(TAG, "checkVersion: has new version ")
                    onCheckListener?.onCheck(json)
                }

                else -> {
                    if (!silent) {
                        ToastUtil.info(mContext, message)
                    }
                }
            }
            return true
        }
        return false
    }
}